<?php

namespace app\storeapi\controller;
use think\Db;

/**
 * 爆品礼扫码核销
 * Class Goods
 * @package app\store\controller
 */
class Scan extends Controller
{
    /**
     * 订单详情
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function orderInfo()
    {
        $param = $this->postData();
        if(empty($param['order_id'])){
            return $this->renderError('参数错误');
        }
        $info = db('gifts_order')
            ->alias('a')
            ->join('yoshop_user b','a.user_id=b.user_id')
            ->join('yoshop_gifts_order_goods c','a.order_id=c.order_id')
            ->join('yoshop_upload_file d','c.image_id=d.file_id')
            ->field('a.order_id,a.write_status,a.order_no,a.pay_price,a.line_price,a.pay_status,c.start_time,c.end_time,c.gifts_discription,c.gifts_title,b.nickName,d.file_url,d.file_name,d.storage')
            ->where(['a.order_id'=>$param['order_id']])
            ->find();
        if(empty($info)){
            return $this->renderError('核销订单不存在');
        }
        if($info['write_status']==20){
            return $this->renderError('该订单已经核销过了');
        }
        
        $info['start_time'] = date('Y-m-d',$info['start_time']);
        $info['end_time'] = date('Y-m-d',$info['end_time']);
         if($info['storage']==="local"){
             $info['file_url'] = base_url().'uploads/'. $info['file_name'];
        }else{
            $info['file_url'] = $info['file_url']."/".$info['file_name'];
        }
        return $this->renderSuccess($info);

    }


    /**
     * 订单核销
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function write()
    {
        $param = $this->postData();

        if(empty($param['order_id'])){
            return $this->renderError('参数错误');
        }
        $info = db('gifts_order')->where(['order_id'=>$param['order_id'],'write_status'=>10])->find();
        if(empty($info)){
            return $this->renderError('该订单已经核销过了');
        }
        $flag = db('gifts_order')->where(['order_id'=>$param['order_id']])->update(['write_status'=>20,'write_time'=>time()]);
        db('user_gifts')->where(['order_id'=>$param['order_id'],'type'=>0])->update(['write_status'=>20]);
        if($flag){
            return $this->renderSuccess([],'核销成功');
        }else{
            return $this->renderError('核销失败');
        }


    }

}



